import { Module } from "vuex";
// 该泛型需结合两个参数
import IProductState from "./type";
import { IRootState } from "@/store/types";

import {
  addGoods,
  updataGoods,
  deleteGoods,
  getGoods,
  updataStatus
} from "@/service/main/goods";
const systemModule: Module<IProductState, IRootState> = {
  // 提供一个作用域
  namespaced: true,
  state() {
    return {
      goodsList: []
    };
  },
  actions: {
    // 添加
    async addGoods({ commit, dispatch }, data) {
      console.log("添加商品请求", data);
      let res = await addGoods(data);
      res = res.data;
      if (res.total == 200) {
        return Promise.resolve("ok");
      } else {
        return Promise.reject(new Error(res.message || "fail"));
      }
    },
    // 修改
    async editGoods({ commit }, data) {
      console.log("修改商品请求");
      const res: any = await updataGoods(data);
      console.log(res);
      if (res.total == 200) {
        return Promise.resolve("ok");
      } else {
        return Promise.reject(new Error(res.message || "fail"));
      }
    },
    // 删除
    async deleteGoods({ commit, dispatch }, id) {
      let res = await deleteGoods(id);
      res = res.data;
      if (res.total == 200) {
        return Promise.resolve("ok");
      } else {
        return Promise.reject(new Error(res.message || "fail"));
      }
    },
    // 修改状态
    async upStatus({ commit }, data) {
      let res = await updataStatus(data);
      res = res.data;
      if (res.total == 200) {
        return Promise.resolve("ok");
      } else {
        return Promise.reject(new Error(res.message || "fail"));
      }
    },
    // 获取商品列表
    async getGoods({ commit }, data) {
      let res: any = await getGoods(data);
      res = res.data;
      if (res.total) {
        if (res.data instanceof Array) {
          commit("GETGOODS", res.data);
        }
        return Promise.resolve("ok");
      } else {
        return Promise.reject(new Error(res.message || "fail"));
      }
    }
  },
  mutations: {
    // 存储商品数据
    GETGOODS(state, data) {
      state.goodsList = data;
    }
  },
  getters: {
    getGoodsList(state) {
      return state.goodsList || [];
    }
  }
};
export default systemModule;
